import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:edu_assistant/api/data_service.dart';
import 'package:edu_assistant/model/file_item_entity.dart';
import 'package:edu_assistant/widgets/common_image_view.dart';

class FilterableListPage<T extends ScrollNotification> extends StatefulWidget {
  @override
  _FilterableListPageState createState() => _FilterableListPageState();
}

class _FilterableListPageState extends State<FilterableListPage>
    with
        AutomaticKeepAliveClientMixin<FilterableListPage>,
        SingleTickerProviderStateMixin {
  String fileType = "";
  int page = 1;
  int size = 10;
  bool lastPage = true;
  List<FileItemEntity> dataList = [];
  late EasyRefreshController _controller;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
  List<TextStyle> textStyles = [
    TextStyle(color: Colors.red),
    TextStyle(color: Colors.black54),
    TextStyle(color: Colors.black54),
    TextStyle(color: Colors.black54)
  ];
  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.white,
      endDrawer: Drawer(
        backgroundColor: Colors.lime,
        elevation: 10.0,
        child: ListView(
          children: <Widget>[
            UserAccountsDrawerHeader(
              accountName: Text('John Doe'),
              accountEmail: Text('johndoe@example.com'),
              currentAccountPicture: CircleAvatar(
                backgroundImage:
                    NetworkImage('https://example.com/profile.jpg'),
              ),
            ),
            ListTile(
              leading: Icon(Icons.home),
              title: Text('Home'),
              onTap: () {
                // 处理点击事件
                // Navigator.pop(context); // 关闭Drawer
              },
            ),
            ListTile(
              leading: Icon(Icons.settings),
              title: Text('Settings'),
              onTap: () {
                // 处理点击事件
                // Navigator.pop(context); // 关闭Drawer
              },
            ),
          ],
        ),
      ),
      body: Stack(children: <Widget>[_getFileListWidget(), _subHeaderWidget()]),
    );
  }

  Widget _getFileListWidget() {
    return Container(
      padding: EdgeInsets.all(0),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(45)),
      child: EasyRefresh(
        controller: _controller,
        refreshOnStart: true,
        header: const ClassicHeader(
            showMessage: false,
            dragText: "下拉刷新",
            armedText: "释放刷新",
            readyText: "刷新中",
            processingText: "刷新中",
            processedText: "刷新完成"),
        footer: const ClassicFooter(
            showMessage: false,
            dragText: "上划加载",
            armedText: "释放加载",
            readyText: "加载中",
            processingText: "加载中",
            processedText: "加载完成",
            noMoreText: "--到底啦--"),
        onRefresh: () async {
          page = 1;
          await DataService.getFilePage(
                  {"page": page, "size": size, "fileType": "image/jpeg"})
              .then((value) {
            int totalPages = (value.total! + size - 1) ~/ size;
            if (totalPages == 1) {
              lastPage = true;
            } else {
              lastPage = false;
              page++;
            }
            dataList.clear();
            value.rows?.forEach((element) {
              dataList.add(element);
            });
            setState(() {});
          });
          _controller.finishRefresh();
          _controller.resetFooter();
        },
        onLoad: () async {
          await DataService.getFilePage(
                  {"page": page, "size": size, "fileType": "image/jpeg"})
              .then((value) {
            int totalPages = (value.total! + size - 1) ~/ size;
            if (totalPages <= page) {
              lastPage = true;
            } else {
              lastPage = false;
              page++;
            }
            value.rows?.forEach((element) {
              dataList.add(element);
            });
            setState(() {});
          });
          _controller.finishLoad(
              lastPage ? IndicatorResult.noMore : IndicatorResult.success);
        },
        child: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: 1.0,
            crossAxisSpacing: 1.0,
            childAspectRatio: 0.7,
          ),
          itemCount: dataList.length,
          itemBuilder: (context, index) {
            return Container(
              color: Colors.green,
              padding: EdgeInsets.all(1),
              margin: EdgeInsets.all(1),
              child: CommonImageView(
                  url: dataList[index].url, height: 200, width: 50),
            );
          },
        ),
      ),
    );
  }

//筛选导航
  Widget _subHeaderWidget() {
    return Positioned(
      top: ScreenUtil().setHeight(30),
      height: ScreenUtil().setHeight(50),
      width: ScreenUtil().screenWidth,
      child: Container(
        width: ScreenUtil().screenWidth,
        height: ScreenUtil().setHeight(50),
        // color: Colors.red,
        decoration: BoxDecoration(
            color: Color.fromRGBO(255, 255, 255, 1),
            border: Border(
                bottom: BorderSide(
                    width: 1, color: Color.fromRGBO(233, 233, 233, 0.9)))),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: InkWell(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(0, ScreenUtil().setHeight(16), 0,
                      ScreenUtil().setWidth(16)),
                  child: Text(
                    "综合",
                    textAlign: TextAlign.center,
                    style: textStyles[0],
                  ),
                ),
                onTap: () {
                  focusFilter(0);
                },
              ),
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(0, ScreenUtil().setHeight(16), 0,
                      ScreenUtil().setHeight(16)),
                  child: Text(
                    "销量",
                    textAlign: TextAlign.center,
                    style: textStyles[1],
                  ),
                ),
                onTap: () {
                  focusFilter(1);
                },
              ),
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(0, ScreenUtil().setHeight(16), 0,
                      ScreenUtil().setHeight(16)),
                  child: Text(
                    "价格",
                    textAlign: TextAlign.center,
                    style: textStyles[2],
                  ),
                ),
                onTap: () {
                  focusFilter(2);
                },
              ),
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(0, ScreenUtil().setHeight(16), 0,
                      ScreenUtil().setHeight(16)),
                  child: Text(
                    "筛选",
                    textAlign: TextAlign.center,
                    style: textStyles[3],
                  ),
                ),
                onTap: () {
                  _scaffoldKey.currentState?.openEndDrawer();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void focusFilter(int i) {
    textStyles[0] = TextStyle(color: Colors.black54);
    textStyles[1] = TextStyle(color: Colors.black54);
    textStyles[2] = TextStyle(color: Colors.black54);
    textStyles[3] = TextStyle(color: Colors.black54);
    setState(() {
      textStyles[i] = TextStyle(color: Colors.red);
    });
  }

  @override
  bool get wantKeepAlive => true;
}
